package pers.cz.redis;

import pers.cz.pub.BeanHelper;
import pers.cz.spring.SpringContextUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.net.InetSocketAddress;

/**
 * 心跳检测
 * @program: Reids
 * @description: ClientStarter
 * @author: Cheng Zhi
 * @create: 2021-07-26 17:20
 **/
public class ClientStarter {

    Logger logger = LoggerFactory.getLogger(ClientStarter.class);

    int i = 0;
    private Bootstrap bootstrap;
    private int times = 0;
    private String host;
    private Integer port;

    public ClientStarter(Bootstrap bootstrap, String host, Integer port) {
        this.host = host;
        this.port = port;
        this.bootstrap = bootstrap;
        ClientStarter clientStarter = this;
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        //发送消息频率。单位秒。此设置是60秒发送一次消息
                        ch.pipeline().addLast(new IdleStateHandler(60, 60, 60));
                        ch.pipeline().addLast(new HeartBeatClientHandler(clientStarter));
                    }
                });
    }

    public void connect() {
        i ++;
        ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port));
        channelFuture.addListener(future ->{
            if (future.isSuccess()) {
                logger.debug("connect to server success" + "----" + i);
                // 重新连接成功,如果i!=1表示不是第一次启动。
                if (i != 1) {

                    RedisConfig config = new RedisConfig();
                    JedisPool jedisPool = config.redisPoolFactoryGeneral();
                    // 网络断开会导致redis断开，这里重新生成一个连接池，替换掉老的连接池
                    BeanHelper.replaceBean("jedisPool", jedisPool);

                    JedisPool bean = SpringContextUtil.getBean(JedisPool.class);
                    Jedis resource = bean.getResource();
                }
            } else {
                logger.debug("connect to server failed,try times:" + ++times + "----" + i);
                connect();
            }
        });
    }
}
